import json
import os
from game_objects import GameObject

# 颜色常量
WOOD_COLOR = (205, 133, 63)
STONE_COLOR = (169, 169, 169)
GLASS_COLOR = (173, 216, 230)

class Level:
    def __init__(self, name, description, objects, stars_requirements, background="default"):
        self.name = name
        self.description = description
        self.objects = objects
        self.stars_requirements = stars_requirements  # [1星分数, 2星分数, 3星分数]
        self.background = background
        self.high_score = 0
        self.stars = 0

    @staticmethod
    def create_objects(level_data):
        """从关卡数据创建游戏对象"""
        objects = []
        for obj in level_data["objects"]:
            objects.append(GameObject(
                obj["x"], obj["y"],
                obj["width"], obj["height"],
                obj["type"],
                {
                    "wood": WOOD_COLOR,
                    "stone": STONE_COLOR,
                    "glass": GLASS_COLOR
                }[obj["type"]],
                obj.get("health", 100)
            ))
        return objects

class LevelManager:
    def __init__(self):
        self.levels = []
        self.current_level_index = 0
        self.load_levels()
        self.load_progress()

    def load_levels(self):
        """加载所有关卡配置"""
        levels_data = [
            {
                "name": "新手关卡",
                "description": "学习基本玩法",
                "objects": [
                    {"x": 800, "y": 600, "width": 100, "height": 40, "type": "wood"},
                    {"x": 800, "y": 560, "width": 100, "height": 40, "type": "glass"}
                ],
                "stars_requirements": [100, 200, 300]
            },
            {
                "name": "双塔挑战",
                "description": "摧毁两座塔",
                "objects": [
                    # 左塔
                    {"x": 600, "y": 600, "width": 60, "height": 40, "type": "stone"},
                    {"x": 600, "y": 560, "width": 60, "height": 40, "type": "wood"},
                    {"x": 600, "y": 520, "width": 60, "height": 40, "type": "glass"},
                    # 右塔
                    {"x": 800, "y": 600, "width": 60, "height": 40, "type": "stone"},
                    {"x": 800, "y": 560, "width": 60, "height": 40, "type": "wood"},
                    {"x": 800, "y": 520, "width": 60, "height": 40, "type": "glass"}
                ],
                "stars_requirements": [200, 400, 600]
            },
            {
                "name": "金字塔",
                "description": "挑战复杂结构",
                "objects": [
                    # 底层
                    {"x": 600, "y": 600, "width": 300, "height": 40, "type": "stone"},
                    # 第二层
                    {"x": 650, "y": 560, "width": 200, "height": 40, "type": "wood"},
                    # 第三层
                    {"x": 700, "y": 520, "width": 100, "height": 40, "type": "wood"},
                    # 顶层
                    {"x": 725, "y": 480, "width": 50, "height": 40, "type": "glass"}
                ],
                "stars_requirements": [300, 600, 900]
            },
            {
                "name": "玻璃城堡",
                "description": "精准打击",
                "objects": [
                    # 底座
                    {"x": 600, "y": 600, "width": 300, "height": 40, "type": "stone"},
                    # 玻璃墙
                    {"x": 650, "y": 560, "width": 40, "height": 120, "type": "glass"},
                    {"x": 750, "y": 560, "width": 40, "height": 120, "type": "glass"},
                    {"x": 850, "y": 560, "width": 40, "height": 120, "type": "glass"},
                    # 顶部装饰
                    {"x": 650, "y": 440, "width": 40, "height": 40, "type": "glass"},
                    {"x": 750, "y": 440, "width": 40, "height": 40, "type": "glass"},
                    {"x": 850, "y": 440, "width": 40, "height": 40, "type": "glass"}
                ],
                "stars_requirements": [400, 800, 1200]
            }
        ]

        for data in levels_data:
            self.levels.append(Level(
                data["name"],
                data["description"],
                Level.create_objects(data),
                data["stars_requirements"],
                data.get("background", "default")
            ))

    def load_progress(self):
        """加载游戏进度"""
        progress_file = os.path.join(os.path.dirname(__file__), '..', 'data', 'progress.json')
        os.makedirs(os.path.dirname(progress_file), exist_ok=True)
        
        if os.path.exists(progress_file):
            try:
                with open(progress_file, 'r') as f:
                    progress = json.load(f)
                    for i, level_progress in enumerate(progress["levels"]):
                        if i < len(self.levels):
                            self.levels[i].high_score = level_progress["high_score"]
                            self.levels[i].stars = level_progress["stars"]
            except:
                print("无法加载进度文件")

    def save_progress(self):
        """保存游戏进度"""
        progress_file = os.path.join(os.path.dirname(__file__), '..', 'data', 'progress.json')
        progress = {
            "levels": [
                {
                    "high_score": level.high_score,
                    "stars": level.stars
                }
                for level in self.levels
            ]
        }
        
        try:
            with open(progress_file, 'w') as f:
                json.dump(progress, f)
        except:
            print("无法保存进度文件")

    def update_level_progress(self, score):
        """更新当前关卡进度"""
        level = self.levels[self.current_level_index]
        if score > level.high_score:
            level.high_score = score
            # 更新星级
            for i, requirement in enumerate(reversed(level.stars_requirements)):
                if score >= requirement:
                    level.stars = 3 - i
                    break
            self.save_progress()

    def get_current_level(self):
        """获取当前关卡"""
        return self.levels[self.current_level_index]

    def next_level(self):
        """切换到下一关"""
        if self.current_level_index < len(self.levels) - 1:
            self.current_level_index += 1
            return True
        return False

    def previous_level(self):
        """切换到上一关"""
        if self.current_level_index > 0:
            self.current_level_index -= 1
            return True
        return False

    def is_level_unlocked(self, index):
        """检查关卡是否解锁"""
        if index == 0:
            return True
        return index < len(self.levels) and self.levels[index - 1].stars > 0